package com.tanhua.dubbo.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.pojo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Collections;
import java.util.List;

@DubboService(version = "1.0.0")
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    private static final String VISITOR_REDIS_KEY = "VISITOR_USER";

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 保存访客数据
     *
     * @param userId        我的id
     * @param visitorUserId 访客id
     * @param from          来源
     * @return
     */
    @Override
    public String saveVisitor(Long userId, Long visitorUserId, String from) {

        //查询访客用户在今天是否已经记录过，如果已经记录过，不再记录
        String today = DateUtil.today();
        Long minDate = DateUtil.parseDateTime(today + " 00:00:00").getTime();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();

        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("visitorUserId").is(visitorUserId)
                .andOperator(Criteria.where("date").gte(minDate),
                        Criteria.where("date").lte(maxDate)
                ));

        long count = this.mongoTemplate.count(query, Visitors.class);
        if (count > 0) {
            return null;
        }

        Visitors visitors = new Visitors();
        visitors.setFrom(from);
        visitors.setVisitorUserId(visitorUserId);
        visitors.setUserId(userId);
        visitors.setDate(System.currentTimeMillis());
        visitors.setId(ObjectId.get());

        this.mongoTemplate.save(visitors);
        return visitors.getId().toHexString();
    }
    /**
     * 查询我的访客数据
     *
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> queryMyVisitor(Long userId) {

        // 上一次查询列表的时间
        Long date = Convert.toLong(this.redisTemplate.opsForHash().get(VISITOR_REDIS_KEY, String.valueOf(userId)));

        Query query = Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Order.desc("date"))).limit(5);
        if (ObjectUtil.isNotEmpty(date)) {
            //如果有时间，加入到查询条件中
            query.addCriteria(Criteria.where("date").gte(date));
        }

        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        if (ObjectUtil.isEmpty(visitorsList)){
            return Collections.emptyList();
        }
        List<Object> visitorUserId = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        Query queryReco = Query.query(Criteria.where("toUserId").is(userId).and("UserId").in(visitorUserId));
        List<RecommendUser> recommendUsers = this.mongoTemplate.find(queryReco, RecommendUser.class);
        for (Visitors visitors : visitorsList) {
            for (RecommendUser recommendUser : recommendUsers) {
                if (ObjectUtil.equal(visitors.getUserId(),recommendUser.getUserId())){
                    visitors.setScore(recommendUser.getScore());
                    break;
                }
            }
        }
        //  return this.mongoTemplate.find(query, Visitors.class);
        return visitorsList;
    }

    /**
     * 查询我的访客列表
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> queryMyVisitorList(Long userId) {

        Query query= Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("date")));
        List<Visitors> visitorsList = this.mongoTemplate.find(query, Visitors.class);
        if (ObjectUtil.isEmpty(visitorsList)){
            return Collections.emptyList();
        }
        List<Object> visitorUserId = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        Query queryReco = Query.query(Criteria.where("toUserId").is(userId).and("UserId").in(visitorUserId));
        List<RecommendUser> recommendUsers = this.mongoTemplate.find(queryReco, RecommendUser.class);
        for (Visitors visitors : visitorsList) {
            for (RecommendUser recommendUser : recommendUsers) {
                if (ObjectUtil.equal(visitors.getUserId(),recommendUser.getUserId())){
                    visitors.setScore(recommendUser.getScore());
                    break;
                }
            }
        }
        //  return this.mongoTemplate.find(query, Visitors.class);
        return visitorsList;
    }
}
